package com.aube.interact.controller;

import android.content.Context;
import android.view.ViewGroup;

import com.aube.interact.GoodsHotpotLayout;
import com.aube.interact.model.GoodsFavorListModel;
import com.aube.interact.model.GoodsItem;
import com.aube.interact.model.GoodsListModel;
import com.aube.interact.model.GoodsModel;
import com.aube.interact.model.GoodsRoute;
import com.aube.interact.util.Utils;
import com.aube.rvi.CommonDataLoader;
import com.aube.rvi.net.AubeError;
import com.aube.rvi.net.ResponseListener;
import com.aube.rvi.net.StringRequest;
import com.aube.rvi.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

/**
 * Created by huyaonan on 16/3/23.
 */
public class GoodsCardController extends AbstractController<GoodsModel> {

    private GoodsListModel mGoodsData;

    public GoodsCardController(Context context, ViewGroup mRoot, String mVideoId, IControllerCallback callback) {
        super(context, mRoot, mVideoId, callback);

        ((GoodsHotpotLayout) mCardRoot).bindVideo(mVideoId);
    }

    @Override
    public boolean setupCards(long selectedIndex, boolean freshData, boolean autoBegin) {
//        mCurrentData = null;
        if(setupCards(selectedIndex, autoBegin))
            return true;

        if(freshData) {
            loadGoodsTimeLine(selectedIndex);
            return true;
        }

        return false;
    }

    public boolean setupCards(long selectedIndex, boolean autoBegin) {
        clearCardsList();
        if(mGoodsData == null || mGoodsData.data == null)
            return false;
        synchronized (mCardsList) {
            mCardsList.clear();
            long currentSecond = selectedIndex / 1000;
            for(GoodsModel item : mGoodsData.data) {
                if(item.endSeconds <= currentSecond)
                    continue;
                mCardsList.add(item);
            }

            if(!autoBegin)
                locateCardByTime(selectedIndex);
        }
        return true;
    }

    private long currentSecond=0;
    @Override
    public boolean locateCardByTime(long current) {
        if(current < 0)
            return manageCard(null);

        synchronized (mCardsList) {
            currentSecond = current / 1000;

            if(mCurrentData != null) {
                if(mCurrentData.endSeconds <= currentSecond || mCurrentData.startSeconds > currentSecond)
                    mCurrentData = null;
                else
                    return manageCard(mCurrentData, currentSecond);
            }

            if(mCardsList.size() == 0)
                return manageCard(null);

            GoodsModel firstItem = mCardsList.get(0);
            if(firstItem.startSeconds <= currentSecond && firstItem.endSeconds > currentSecond) {
                Utils.Log(TAG, "GOODS____load card at time:" + currentSecond);
                mCardsList.remove(0);
                return manageCard(firstItem, currentSecond);
            } else if(firstItem.endSeconds <= currentSecond) {
                mCardsList.remove(0);
            }

            return manageCard(null);
        }
    }

    @Override
    public boolean manageCard(GoodsModel data) {
        return manageCard(data, 0);
    }

    public boolean manageCard(GoodsModel data, long current) {
        if(data != null) {
            if(mCurrentData != null)  {
                if(mCurrentData.rid.equalsIgnoreCase(data.rid)) {
//                    Utils.Log(TAG, "GOODS____update");
                } else {
                    mCurrentData = data;
                    appendToScreen(data, current);
                }
            } else {
                mCurrentData = data;
                appendToScreen(data, current);
            }
        } else {
            mCurrentData = null;
            if(mCardRoot.getChildCount() != 0) {
                removeFromScreen();
            }
        }
        return true;
    }

    public void removeFromScreen() {
        if(mCardRoot != null)
            ((GoodsHotpotLayout) mCardRoot).onDestroy();
    }

    @Override
    public void appendToScreen(final GoodsModel data) {
        appendToScreen(data, 0);
    }

    protected void appendToScreen(final GoodsModel data, final long current) {
        removeFromScreen();
        try {
//            GoodsRoute route = setupRoutesStack(current);
            setupPosStack(current);
//            ((GoodsHotpotLayout) mCardRoot).showHotpot(data, route, new GoodsHotpotLayout.IAddFavorListener() {
            ((GoodsHotpotLayout) mCardRoot).showHotpot(data, new GoodsHotpotLayout.IAddFavorListener() {
                @Override
                public void doFavorEvent(GoodsItem item) {
                    //add goodsitem
                    addFavor(item._id, true);

                    List<GoodsItem> list = new ArrayList<>();
                    list.add(item);
                    if (iControllerCallback != null)
                        iControllerCallback.onGoodsAdd(list);
                }

                @Override
                public void cancelFavor(String id) {
                    removeFavor(id);

                    if (iControllerCallback != null)
                        iControllerCallback.cancelGoods(id);
                }

                @Override
                public int[] getCartLocation() {
                    if (iControllerCallback != null)
                        return iControllerCallback.getCartLocation();
                    return null;
                }

                @Override
                public float[] getCardPosition() {
                    if(mListPosStack == null)
                        return null;
                    synchronized (mListPosStack) {
                        if(mListPosStack.size() == 0)
                            return null;

                        GoodsRoute route;
                        while (true) {
                            route = mListPosStack.pop();
                            if (route == null)
                                return null;

                            GoodsRoute item = mListPosStack.peek();
                            if(item == null) {
                                mListPosStack.push(route);
                                return route.get();
                            }

                            if(currentSecond <= route.s) {
                                mListPosStack.push(route);
                                return route.get();
                            } else if(currentSecond <= item.s) {
                                mListPosStack.push(route);
                                return route.get();
                            } else {
                                //continue
                            }
                        }
                    }
                }

                @Override
                public int getProgress() {
                    if (iControllerCallback != null)
                        return (int) iControllerCallback.getCurrentProgress();
                    return 0;
                }

                @Override
                public void hideFavorCart() {
                    if(iControllerCallback != null)
                        iControllerCallback.hideFavorCart();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Stack<GoodsRoute> mListPosStack = null;

    private void setupPosStack(long current) {
        mListPosStack = new Stack<>();
        synchronized(mListPosStack) {
            if (mCurrentData == null && mCurrentData.rectangleTrajectoryList == null)
                return;

            for (int i = mCurrentData.rectangleTrajectoryList.size() - 1; i >= 0; i--) {
                GoodsRoute item = mCurrentData.rectangleTrajectoryList.get(i);
                if (item.s >= current)
                    mListPosStack.push(item);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void loadGoodsTimeLine(final long selectedIndex) {
        if(StringUtils.isBlank(mVideoId)) {
            Utils.showToast(context, "没有节目");
            return;
        }
        HashMap<String, String> parameterMap = new HashMap<>();
//        parameterMap.put("method", "com.aube.goods.timeline.goodsListByVideoid");
        parameterMap.put("method", "com.aube.goods.timeline.goods.list");
        parameterMap.put("videoid", mVideoId);
        StringRequest request = new StringRequest(API_ROUTER, parameterMap, new ResponseListener<String>() {

            @Override
            public void onResponse(String s) {
                GoodsListModel response = GoodsListModel.parse(s);
                if(response.success()) {
                    mGoodsData = response;
                    setupCards(selectedIndex, true);
                } else {
//                    Utils.showToast(context, response.errormsg);
                }
            }

            @Override
            public void onErrorResponse(AubeError error) {
            }

            @Override
            public void onStart() {
            }
        });
        request.setTag(TAG);
        CommonDataLoader.getInstance(context).startHttpLoader(request);

        loadFavorGoods();
    }

    public void addFavor(String goodsId, boolean yes) {
        if(StringUtils.isBlank(mVideoId)) {
            Utils.showToast(context, "没有节目");
            return;
        }
        HashMap<String, String> parameterMap = new HashMap<>();
        parameterMap.put("method", "com.aube.goods.favorites");
        parameterMap.put("videoid", mVideoId);
        parameterMap.put("goodsid", goodsId);
        parameterMap.put("state", yes?"1":"0");
        StringRequest request = new StringRequest(API_ROUTER, parameterMap, new ResponseListener<String>() {

            @Override
            public void onResponse(String response) {
//                if(response.success()) {
////                    Utils.showToast(context, response.data);
////                    loadFavorGoods();
//                } else {
////                    Utils.showToast(context, response.errormsg);
//                }
            }

            @Override
            public void onErrorResponse(AubeError error) {
            }

            @Override
            public void onStart() {
            }
        });
        request.setTag(TAG);
        CommonDataLoader.getInstance(context).startHttpLoader(request);
    }

    public void loadFavorGoods() {
        if(StringUtils.isBlank(mVideoId)) {
            Utils.showToast(context, "没有节目");
            return;
        }
        HashMap<String, String> parameterMap = new HashMap<>();
        parameterMap.put("method", "com.aube.goods.favoritesGoodsList");
        parameterMap.put("videoid", mVideoId);
        StringRequest request = new StringRequest(API_ROUTER, parameterMap, new ResponseListener<String>() {

            @Override
            public void onResponse(String s) {
                GoodsFavorListModel response = GoodsFavorListModel.parse(s);
                if(response.success()) {
                    if(response.getSize() == 0)
                        return;
                    DataManager.getInstance(context).update(response.getGoodsList());
                }
            }

            @Override
            public void onErrorResponse(AubeError error) {
            }

            @Override
            public void onStart() {
            }
        });
        request.setTag(TAG);
        CommonDataLoader.getInstance(context).startHttpLoader(request);
    }

    private void removeFavor(String id) {
        addFavor(id, false);
    }

}
